import React, { useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Users, ShieldCheck, HardHat, Truck } from 'lucide-react';

const categoryConfig = {
  '项目管理单位人员': { icon: ShieldCheck, color: 'text-blue-600', bgColor: 'bg-blue-50' },
  '监理单位人员': { icon: HardHat, color: 'text-green-600', bgColor: 'bg-green-50' },
  '施工单位人员': { icon: Truck, color: 'text-orange-600', bgColor: 'bg-orange-50' },
};

export default function SchemePersonnelManager({ rolesConfig, personnelData = [], onUpdate }) {
  const handlePersonnelChange = (roleCategory, roleName, field, value) => {
    const updatedPersonnel = [...personnelData];
    const existingEntryIndex = updatedPersonnel.findIndex(
      p => p.role_category === roleCategory && p.role_name === roleName
    );

    if (existingEntryIndex !== -1) {
      updatedPersonnel[existingEntryIndex] = {
        ...updatedPersonnel[existingEntryIndex],
        [field]: value,
      };
    } else {
      updatedPersonnel.push({
        role_category: roleCategory,
        role_name: roleName,
        [field]: value,
      });
    }

    onUpdate('responsible_personnel', updatedPersonnel);
  };

  const getPersonnelValue = (roleCategory, roleName, field) => {
    const entry = personnelData.find(
      p => p.role_category === roleCategory && p.role_name === roleName
    );
    return entry ? entry[field] || '' : '';
  };
  
  const groupedRoles = useMemo(() => {
    // Check if rolesConfig has the wrapped structure with roles array
    const roles = rolesConfig?.roles || rolesConfig || [];
    
    if (!Array.isArray(roles) || roles.length === 0) return {};
    
    const groups = roles.reduce((acc, role) => {
      const category = role.category || '未分类';
      if (!acc[category]) {
        acc[category] = [];
      }
      acc[category].push(role);
      return acc;
    }, {});
    
    // Sort roles within each category by sort_order
    for (const category in groups) {
      groups[category].sort((a, b) => (a.sort_order || 99) - (b.sort_order || 99));
    }
    
    return groups;
  }, [rolesConfig]);

  const roles = rolesConfig?.roles || rolesConfig || [];
  if (!Array.isArray(roles) || roles.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Users className="w-5 h-5 text-gray-500" />
            施工方案责任人
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-gray-500 text-sm">
            暂无责任人角色配置。请先前往【系统配置】-【责任人角色】页面添加相关配置。
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base">
          <Users className="w-5 h-5 text-gray-500" />
          施工方案责任人
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {Object.entries(groupedRoles).map(([category, roles]) => {
          const config = categoryConfig[category] || { icon: Users, color: 'text-gray-600', bgColor: 'bg-gray-50' };
          const Icon = config.icon;
          return (
            <div key={category} className={`p-4 border rounded-lg ${config.bgColor}`}>
              <h3 className={`flex items-center gap-2 font-semibold mb-4 ${config.color}`}>
                <Icon className="w-5 h-5" />
                {category}
              </h3>
              <div className="space-y-4">
                {roles.map(role => (
                  <div key={role.role_name} className="grid grid-cols-1 md:grid-cols-3 gap-x-4 gap-y-2 items-center">
                    <div className="md:col-span-1">
                      <Label className="font-normal text-gray-700 flex items-center">
                        {role.role_name}
                        {role.is_emergency_member && (
                          <Badge variant="outline" className="ml-2 text-red-600 border-red-200 bg-red-50 text-xs">应急</Badge>
                        )}
                      </Label>
                    </div>
                    <div className="md:col-span-2 grid grid-cols-2 gap-2">
                       <Input
                          placeholder="填写姓名"
                          value={getPersonnelValue(category, role.role_name, 'person_name')}
                          onChange={(e) => handlePersonnelChange(category, role.role_name, 'person_name', e.target.value)}
                        />
                        <Input
                          placeholder="填写联系方式"
                          value={getPersonnelValue(category, role.role_name, 'contact_info')}
                          onChange={(e) => handlePersonnelChange(category, role.role_name, 'contact_info', e.target.value)}
                        />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </CardContent>
    </Card>
  );
}